package com.devplatform.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.devplatform.pojo.article.Article;
import com.devplatform.pojo.article.ArticleShare;
import com.devplatform.pojo.user.UserArticleCollect;
import com.devplatform.pojo.user.UserArticleLike;
import com.devplatform.pojo.vo.DataVo;
import com.devplatform.service.article.*;
import com.devplatform.util.UserContextHolder;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.Map;

@RestController
@RequestMapping("api/interactions")
@RequiredArgsConstructor
public class ArticleInteractionsController {
    private final ArticleInteractionsService articleInteractionsService;
    private final ArticleService articleService;
    private final UserArticleLikeService userArticleLikeService;
    private final UserArticleCollectService userArticleCollectService;
    private final ArticleShareService articleShareService;

    @PostMapping("/likes")
    public DataVo likes(@RequestBody UserArticleLike userArticleLike) {
        Long userId = UserContextHolder.getUserId();
        userArticleLike.setUserId(userId);
        return userArticleLikeService.likes(userArticleLike);
    }

    // 新增：查询是否已点赞
    @GetMapping("/like/status/{articleId}")
    public DataVo<Boolean> getLikeStatus(@PathVariable Long articleId) {
        // 从上下文获取当前登录用户ID（与现有逻辑一致）
        Long userId = UserContextHolder.getUserId();
        if (userId == null) {
            // 未登录用户默认未点赞
            return DataVo.ok(false);
        }
        // 调用Service查询状态
        return userArticleLikeService.isLiked(userId, articleId);
    }

    @GetMapping("/collect/status/{articleId}")
    public DataVo<Boolean> getCollectStatus(@PathVariable Long articleId) {
        // 从上下文获取当前登录用户ID（与现有逻辑一致）
        Long userId = UserContextHolder.getUserId();
        if (userId == null) {
            // 未登录用户默认未收藏
            return DataVo.ok(false);
        }
        // 调用Service查询状态
        return userArticleCollectService.isCollected(userId, articleId);
    }
    @PostMapping("/collect")
    public DataVo collect(@RequestBody UserArticleCollect userArticleCollect) {
        Long userId = UserContextHolder.getUserId();
        userArticleCollect.setUserId(userId);
        return userArticleCollectService.collect(userArticleCollect);
    }

    @PostMapping("getURL")
    public DataVo getURL(@RequestBody ArticleShare articleShare) {
        return DataVo.ok(articleShareService.generateShareUrl(articleShare.getArticleId()));
    }

    @PostMapping("shareArticle")
    public DataVo shareArticle(@RequestBody ArticleShare articleShare) {
        Long shareUserId = UserContextHolder.getUserId();
        Long articleId = articleShare.getArticleId();
        Long authorId = articleService.getAuthorIdByArticleId(articleId);
        ArticleShare share = new ArticleShare();
        share.setArticleId(articleId);
        share.setUserId(shareUserId);
        share.setAuthorId(authorId);
        share.setShareTime(LocalDateTime.now());
        //修改分享表
        articleShareService.save(share);
        //判断是否已分享
        LambdaQueryWrapper<ArticleShare> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ArticleShare::getArticleId, articleId).eq(ArticleShare::getUserId, shareUserId);
        //返回0/1
        Long hasShared = articleShareService.count(queryWrapper);
        if (hasShared <= 0) {
            //分享后作者加积分
            articleShareService.confirmShare(articleId);
            return DataVo.ok();
        }
        return DataVo.ok();
    }

    // 新增：统计文章浏览量
    @PostMapping("/views")
    public DataVo incrementViewCount(@RequestBody Map<String, Long> request) {
        Long articleId = request.get("articleId");
        if (articleId == null) {
            return DataVo.error("文章ID不能为空");
        }
        // 验证文章是否存在
        Article article = articleService.getById(articleId);
        if (article == null) {
            return DataVo.error("文章不存在");
        }
        // 调用Service层更新浏览量
        boolean success = articleInteractionsService.incrementViewCount(articleId);
        return success ? DataVo.ok("浏览量统计成功") : DataVo.error("浏览量统计失败");
    }
}
